package com.example.yingjiguanli_demo.service.impl;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.example.yingjiguanli_demo.mapper.*;
import com.example.yingjiguanli_demo.pojo.*;
import com.example.yingjiguanli_demo.service.IQuestionsService;
import com.example.yingjiguanli_demo.utils.ExcelUtils;
import com.example.yingjiguanli_demo.utils.UserUtils;
import org.apache.poi.ss.formula.functions.T;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.multipart.MultipartFile;

import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author scj
 * @since 2024-11-04
 */
@Service
public class QuestionsServiceImpl extends ServiceImpl<QuestionsMapper, Questions> implements IQuestionsService {

    @Autowired
    private QuestionsMapper questionsMapper;

    @Autowired
    private OptionsMapper optionsMapper;

    @Autowired
    private UserUtils userUtils;

    @Autowired
    private UserAnswersMapper userAnswersMapper;

    @Autowired
    private SubjectsMapper subjectsMapper;

    @Autowired
    private RankingsMapper rankingsMapper;

    /***
     * 导入题目
     * @param questions 题目列表
     * @param options 选项列表
     * @return 导入结果
     */
    @Override
    @Transactional  // 启用事务
    public Result<T> importQuestions(List<Questions> questions, List<Options> options, Integer subjectId) {
        // 校验 subjectId 是否存在于 subjects 表中
        if (subjectsMapper.selectById(subjectId) == null) {
            return Result.failed("无效的科目ID，无法导入题目");
        }
        // 为每个题目设置科目ID
        for (Questions question : questions) {
            question.setSubjectId(subjectId);
        }

        // 批量插入题目
        boolean questionSaved = this.saveBatch(questions);

        // 如果题目插入成功
        if (questionSaved) {
            // 获取已插入题目的 ID
            List<Integer> questionIds = questions.stream()
                    .map(Questions::getQuestionId)
                    .collect(Collectors.toList());

            // 校验 options 列表长度
            if (options.size() != questionIds.size() * 4) {
                return Result.failed("选项数量与题目数量不匹配，每题应有 4 个选项");
            }

            // 为每个选项设置题目 ID
            for (int i = 0; i < options.size(); i++) {
                Options option = options.get(i);
                option.setQuestionId(questionIds.get(i / 4));  // 分配每题的选项
            }

            try {
                // 批量插入选项
                optionsMapper.insertBatchOptions(options);
                return Result.success("导入题目成功");
            } catch (Exception e) {
                // 如果插入选项出错，事务会自动回滚
                log.error("批量插入选项时发生错误", e);
                return Result.failed("导入题目失败：批量插入选项时发生错误");
            }
        }
        return Result.failed("导入题目失败：批量插入题目时发生错误");
    }



    /***
     * 导入题目
     * @param file excel 文件
     * @param subjectId 科目ID
     * @return 导入结果
     */
    @Transactional
    @Override
    public Result<T> importQuestionsFromExcel(MultipartFile file, Integer subjectId) {
        // 校验 subjectId 是否存在于 subjects 表中
        if (subjectsMapper.selectById(subjectId) == null) {
            return Result.failed("无效的科目ID，无法导入题目");
        }

        List<ExcelQuestionDTO> questionDTOs = ExcelUtils.parseExcelFile(file);
        List<Options> options = new ArrayList<>();

        for (ExcelQuestionDTO dto : questionDTOs) {
            Questions question = new Questions();
            question.setQuestionText(dto.getQuestionText());
            question.setQuestionType(dto.getQuestionType());
            question.setIsMultipleChoice(dto.getIsMultipleChoice());
            question.setCorrectAnswer(dto.getCorrectAnswer());
            question.setSubjectId(subjectId);

            // 插入 Question 并获取生成的 question_id
            questionsMapper.questionsInsert(question);
            Integer questionId = question.getQuestionId();

            // 使用 questionId 关联创建 Options
            options.add(createOption(dto.getOptionA(), "A", questionId, dto.getCorrectAnswer()));
            options.add(createOption(dto.getOptionB(), "B", questionId, dto.getCorrectAnswer()));
            options.add(createOption(dto.getOptionC(), "C", questionId, dto.getCorrectAnswer()));
            options.add(createOption(dto.getOptionD(), "D", questionId, dto.getCorrectAnswer()));
        }

        // 批量插入所有 Options
        optionsMapper.insertBatchOptions(options);

        return Result.success("导入成功");
    }






    /***
     * 获取指定数量的题目
     * @param limit 题目数量
     * @return 题目列表
     */
    @Transactional
    @Override
    public Result<List<Questions>> getQuestionsForUser(int subjectId,int limit) {
        // 从数据库中随机获取指定数量的题目
        List<Questions> questions = questionsMapper.getRandomQuestionsBySubject(subjectId,limit);
        for (Questions question : questions) {
            // 获取每个题目的选项并附加到 question 对象中
            List<Options> options = optionsMapper.getOptionsByQuestionId(question.getQuestionId());
            question.setOptions(options); // 假设 Questions 类有 setOptions 方法
        }
        return Result.success(questions);
    }

    /***
     * 检查并记录用户答案
     * @param userId 用户ID
     * @param answerDTOs 用户答案列表
     * @return 检查结果列表
     */
    @Override
    @Transactional
    public List<AnswerResult> checkAndRecordAnswers(int userId, List<AnswerDTO> answerDTOs) {
        List<AnswerResult> results = new ArrayList<>();

        for (AnswerDTO dto : answerDTOs) {
            // 获取题目
            Questions question = questionsMapper.selectById(dto.getQuestionId());
            if (question == null) {
                throw new IllegalArgumentException("Question not found for ID: " + dto.getQuestionId());
            }

            // 检查答案是否正确
            boolean isCorrect = question.getCorrectAnswer().equalsIgnoreCase(dto.getUserAnswer());

            // 记录用户答案
            UserAnswers userAnswerRecord = new UserAnswers();
            userAnswerRecord.setUserId(userId);
            userAnswerRecord.setQuestionId(dto.getQuestionId());
            userAnswerRecord.setUserAnswer(dto.getUserAnswer());
            userAnswerRecord.setIsCorrect(isCorrect);
            userAnswersMapper.insert(userAnswerRecord);

            // 更新用户分数
            updateUserScore(userId, dto.getSubjectId(), isCorrect ? 10 : 0); // 假设每题10分

            // 添加结果到结果列表, 同时添加正确答案
            results.add(new AnswerResult(dto.getQuestionId(), isCorrect, isCorrect ? "答案正确" : "答案错误", question.getCorrectAnswer()));
        }

        return results;
    }

    /***
     * 更新用户分数
     * @param userId 用户ID
     * @param subjectId 科目ID
     * @param scoreToAdd 需要添加的分数
     */
    private void updateUserScore(int userId, int subjectId, int scoreToAdd) {
        // 尝试更新用户的分数
        int updatedRows = rankingsMapper.updateScore(userId, subjectId, scoreToAdd);

        // 如果没有更新行，说明没有记录，插入新记录
        if (updatedRows == 0) {
            rankingsMapper.insertRanking(userId, subjectId, scoreToAdd);
        }
    }

    /***
     * 创建选项
     * @param optionText 选项文本
     * @param label 选项标签
     * @param questionId 题目 ID
     * @param correctAnswer 正确答案
     * @return 选项对象
     */
    private Options createOption(String optionText, String label, Integer questionId, String correctAnswer) {
        Options option = new Options();
        option.setOptionText(optionText);
        option.setOptionLabel(label);
        option.setQuestionId(questionId); // 确保 questionId 已设置
        option.setIsCorrect(label.equals(correctAnswer)); // 将选项标签与正确答案进行比较
        return option;
    }



}
